package main

import (
	"net/http"
	"strconv"
	"github.com/labstack/echo"
	"gopkg.in/mgo.v2"
	json2 "encoding/json"
	"gopkg.in/mgo.v2/bson"
	"github.com/labstack/echo/middleware"
)

func main() {

	session, err := mgo.Dial("")
	if err != nil {
		panic(err)
	}
	defer session.Close()

	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)

	filmC := session.DB("bt").C("film")

	e := echo.New()
	e.GET("/", func(c echo.Context) error {
		return c.String(http.StatusOK, "Hello, World!")
	})

	e.GET("/new/:page/:limit", func(c echo.Context) error {
		page := c.Param("page")
		limit := c.Param("limit")
		p, _ := strconv.Atoi(page)
		l, _ := strconv.Atoi(limit)
		var films [] Film
		filmC.Find(nil).Skip(l * p).Limit(l).All(&films)
		totalPage, _ := filmC.Find(nil).Count()
		r := Result{
			0,
			"success",
			allPage(totalPage,l),
			films,
		}
		rj, _ := json2.Marshal(r)
		return c.JSONBlob(200, rj)
	})

	/********************************搜索*************************************/
	e.GET("/search/:page/:limit/:kw", func(c echo.Context) error {
		page := c.Param("page")
		limit := c.Param("limit")
		kw := c.Param("kw")
		p, _ := strconv.Atoi(page)
		l, _ := strconv.Atoi(limit)

		println(kw)
		var films []Film
		filmC.Find(bson.M{"$or": []bson.M{bson.M{"actor": kw}, bson.M{"name": kw}}}).Skip(l * p).Limit(l).All(&films)
		totalPage, _ := filmC.Find(bson.M{"$or": []bson.M{bson.M{"actor": kw}, bson.M{"name": kw}}}).Count()
		code := 1
		msg := ""
		if totalPage > 0 {
			code = 0
			msg = "success"
		} else {
			code = 1
			msg = "没找到"
		}
		result := Result{
			code,
			msg,
			allPage(totalPage,l),
			films,
		}
		r, _ := json2.Marshal(result)
		return c.JSONBlob(200, r)
	})
	e.Use(middleware.Logger())
	e.Logger.Fatal(e.Start(":1324"))

}

func allPage(p int,limit int) int {

	yu := p %limit
	if yu >= 5 {
		return p/limit + 1
	} else {
		return p/limit
	}
}

type Film struct {
	Poster     string        `json:"poster"`
	Name       string        `json:"name"`
	Director   string        `json:"director"`
	PutTime    string        `json:"putTime"`
	Resolution string        `json:"resolution"`
	Type       []string      `json:"type"`
	Area       []string      `json:"area"`
	Language   []string      `json:"language"`
	Imdb       string        `json:"imdb"`
	Actor      []string      `json:"actor"`
	Introduce  string        `json:"introduce"`
	Ts         []interface{} `json:"ts"`
	Hd         []interface{} `json:"hd"`
	Bd []struct {
		Name string `json:"name"`
		Link string `json:"link"`
	} `json:"bd"`
	Score string `json:"score"`
}

type Result struct {
	Code      int    `json:"code"`
	Msg       string `json:"msg"`
	TotalPage int    `json:"total_page"`
	Data      []Film `json:"data"`
}
